package com.pktechan.api.service.impl;

import com.pktechan.api.base.BaseMapper;
import com.pktechan.api.base.BaseServiceImpl;
import com.pktechan.api.config.YspConfig;
import com.pktechan.api.dao.CloudPointFlowMapper;
import com.pktechan.api.entity.CloudPoint;
import com.pktechan.api.entity.CloudPointFlow;
import com.pktechan.api.entity.CustBase;
import com.pktechan.api.enumeration.*;
import com.pktechan.api.exception.CustomException;
import com.pktechan.api.sendMiniMessage.BaseSendMiniMessage;
import com.pktechan.api.sendMiniMessage.SendMiniMessageStrategy;
import com.pktechan.api.sendMiniMessage.bean.DistributorIntegralIntoMessage;
import com.pktechan.api.sendMiniMessage.enumration.SendMiniMessageEnum;
import com.pktechan.api.service.CloudPointFlowService;
import com.pktechan.api.service.CloudPointService;
import com.pktechan.api.service.CustBaseService;
import com.pktechan.api.service.SendMessageService;
import com.pktechan.api.vo.CloudPointFlowVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Service("cloudPointFlowService")
@Transactional
public class CloudPointFlowServiceImpl extends BaseServiceImpl<CloudPointFlow> implements CloudPointFlowService {
    private static final Logger logger = LoggerFactory.getLogger(CloudPointFlowServiceImpl.class);

    @Autowired
    private CloudPointFlowMapper cloudPointFlowMapper;
    @Autowired
    private CloudPointService cloudPointService;
    @Autowired
    private CustBaseService custBaseService;
    @Autowired
    private SendMessageService sendMessageService;
    @Autowired
    private YspConfig yspConfig;

    /**
     * 由业务类实现
     *
     * @return
     */
    @Override
    public BaseMapper<CloudPointFlow> getBaseMapper() {
        return cloudPointFlowMapper;
    }

    /**
     * 根据订单ID查询应得云积分ID
     *
     * @param tradeOrderId
     * @return
     */
    @Override
    public List<CloudPointFlow> getGenerateListByTradeOrderId(Integer tradeOrderId) {
        return cloudPointFlowMapper.getGenerateListByTradeOrderId(tradeOrderId);
    }

    /**
     * 查看收入明细列表
     *
     * @param custId
     * @return
     */
    @Override
    public List<CloudPointFlowVO> getIncomeDetailsListByCustId(Integer custId) {
        return cloudPointFlowMapper.getIncomeDetailsListByCustId(custId);
    }

    /**
     * 查看兑付明细
     *
     * @param custId
     * @return
     */
    @Override
    public List<CloudPointFlowVO> getCashingDetailsByCustId(Integer custId) {
        return cloudPointFlowMapper.getCashingDetailsByCustId(custId);
    }

    /**
     * 转让兑付
     *
     * @param cloudPointFlow
     */
    @Override
    public void transferableCashing(CloudPointFlow cloudPointFlow, CustBase custBase) {
        logger.info("查询当前登录人积分账户状态");
        CloudPoint outCloudPoint = cloudPointService.getByCustId(custBase.getId());
        if (YesOrNoEnum.NO.getCode().equals(outCloudPoint.getStatus())) {
            throw new CustomException("当前账户异常,不允许转出。");
        }
        logger.info("查询转入配送商信息");
        CustBase intoCustBase = custBaseService.getById(cloudPointFlow.getTransferCustId());
        if (intoCustBase == null) {
            logger.info("配送商id=" + cloudPointFlow.getTransferCustId() + "不存在-------");
            throw new CustomException("配送商不存在");
        }
        if (intoCustBase.getId().equals(custBase.getId())) {
            logger.debug("不可转给自己");
            throw new CustomException("不可转给自己");
        }
//        20240604，酒钻转让无配送商限制了
//        if (!VipTypeEnum.DISTRIBUTOR.getCode().equals(intoCustBase.getVipType())) {
//            logger.info("配送商id=" + cloudPointFlow.getTransferCustId() + "不是配送商");
//            throw new CustomException("您输入的配送商不是配送商，请重新输入");
//        }
        logger.info("查询配送商持仓是否为null");
        CloudPoint intoCloudPoint = cloudPointService.getByCustId(cloudPointFlow.getTransferCustId());
        if (intoCloudPoint == null) {
            logger.info("创建配送商持仓");
            intoCloudPoint = new CloudPoint();
            intoCloudPoint.setAvailableBalance(BigDecimal.ZERO);
            intoCloudPoint.setCustId(cloudPointFlow.getTransferCustId());
            intoCloudPoint.setStatus(CloudPointStatusEnum.VALID.getCode());
            cloudPointService.save(intoCloudPoint);
        }
        if (YesOrNoEnum.NO.getCode().equals(intoCloudPoint.getStatus())) {
            throw new CustomException("对方账户异常,不允许转入。");
        }
        logger.info("转出人的");
        cloudPointFlow.setBalanceAfter(outCloudPoint.getAvailableBalance().subtract(cloudPointFlow.getAmount()));//转让前积分-变动积分=转让后积分
        cloudPointFlow.setBusinessType(CloudPointBusinessTypeEnum.TRANSFER_OUT.getCode());//转出
        //添加转让流水 修改积分
        addCloudPointFlowAndUpdateCloudPoint(cloudPointFlow, outCloudPoint);
        //受让人ID
        cloudPointFlow.setTransferCustId(custBase.getId());
        logger.info("转入配送商的");
        logger.info("添加转入配送商" + cloudPointFlow.getTransferCustId() + "的积分流水");
        //TODO 20240604后，转让有磨损，之后要生对磨损记录
        BigDecimal rate = yspConfig.getCloudPoint().getWithdrawRate();
        BigDecimal into_amt = cloudPointFlow.getAmount().multiply(BigDecimal.ONE.subtract(rate));
        into_amt = into_amt.setScale(0, BigDecimal.ROUND_HALF_UP);

        cloudPointFlow.setAmount(into_amt);
        cloudPointFlow.setBalanceAfter(intoCloudPoint.getAvailableBalance().add(into_amt));//转让前积分+变动积分=转让后积分
        cloudPointFlow.setBusinessType(CloudPointBusinessTypeEnum.TRANSFER_INTO.getCode());//转入
        //添加配送商流水 修改积分
        addCloudPointFlowAndUpdateCloudPoint(cloudPointFlow, intoCloudPoint);
        //配送商接收-配送商-转让换货余额-积分兑换物品-积分通知
        DistributorIntegralIntoMessage distributorIntegralIntoMessage = new DistributorIntegralIntoMessage();
        distributorIntegralIntoMessage.setBalance(cloudPointFlow.getAmount().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        //转出人姓名
        distributorIntegralIntoMessage.setOutName(custBase.getName());
        //转入人openId
        distributorIntegralIntoMessage.setOpenId(intoCustBase.getOpenId());
        SendMiniMessageStrategy distributorIntegralIntoStrategy = BaseSendMiniMessage.getSendMiniMessage(SendMiniMessageEnum.DISTRIBUTOR_INTEGRAL_INTO);
        distributorIntegralIntoStrategy.sendMiniMessageToActiveMq(distributorIntegralIntoMessage);
    }

    /**
     * 酒钻提取，添加流水信息and修改酒钻持仓
     * @param cloudPointFlow
     * @param custBase
     */
//    @Override
//    public void withdrawPoint(CloudPointFlow cloudPointFlow, CustBase custBase) {
//        CloudPoint curPoint = cloudPointService.getByCustId(custBase.getId());
//        cloudPointFlow.setBalanceAfter(curPoint.getAvailableBalance().subtract(cloudPointFlow.getAmount()));//提现前积分-变动积分=提现后积分
//        cloudPointFlow.setBusinessType(CloudPointBusinessTypeEnum.CONSUMPTION.getCode());//提现消费
//        addCloudPointFlowAndUpdateCloudPoint(cloudPointFlow, curPoint);
//    }

    /**
     * 保存积分流水信息and修改积分信息
     *
     * @param cloudPointFlow
     * @param cloudPoint
     */
    public void addCloudPointFlowAndUpdateCloudPoint(CloudPointFlow cloudPointFlow, CloudPoint cloudPoint) {
        logger.info("保存积分流水信息");
        cloudPointFlow.setCloudPointId(cloudPoint.getId());
        cloudPointFlow.setCustId(cloudPoint.getCustId());
        cloudPointFlow.setBalancePre(cloudPoint.getAvailableBalance());//转让前积分
        cloudPointFlow.setStatus(CloudPointFlowStatusEnum.EFFECTIVE.getCode());//有效
        cloudPointFlowMapper.save(cloudPointFlow);
        logger.info("修改积分信息");
        CloudPoint changeInTo = new CloudPoint();
        changeInTo.setId(cloudPoint.getId());
        changeInTo.setAvailableBalance(cloudPointFlow.getBalanceAfter());
        cloudPointService.update(changeInTo);
    }


}
